1 NodeJS中的异步实现

2 libuv中的事件阶段

  • 执行到点的定时器
  • 执行pending回调
  • 执行idle 操作
  • 执行prepare操作
  • 监听I/O请求
  • 执行check操作
  • 执行close回调

3 源码分析

3.1 nodejs 主文件/src/node.cc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
do {
v8_platform.PumpMessageLoop(isolate);
more = uv_run(env.event_loop(), UV_RUN_ONCE);

if (more == false) {
v8_platform.PumpMessageLoop(isolate);
EmitBeforeExit(&env);

// Emit `beforeExit` if the loop became alive either after emitting
// event, or after running some callbacks.
more = uv_loop_alive(env.event_loop());
if (uv_run(env.event_loop(), UV_RUN_NOWAIT) != 0)
more = true;
}
} while (more == true);

3.2 libuv 分平台/deps/uv/src/unix/core.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
int uv_run(uv_loop_t* loop, uv_run_mode mode) {
int timeout;
int r;
int ran_pending;

r = uv__loop_alive(loop);
if (!r)
uv__update_time(loop);

while (r != 0 && loop->stop_flag == 0) {
uv__update_time(loop);
uv__run_timers(loop);
ran_pending = uv__run_pending(loop);
uv__run_idle(loop);
uv__run_prepare(loop);

timeout = 0;
if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
timeout = uv_backend_timeout(loop);

uv__io_poll(loop, timeout);
uv__run_check(loop);
uv__run_closing_handles(loop);

if (mode == UV_RUN_ONCE) {
/* UV_RUN_ONCE implies forward progress: at least one callback must have
* been invoked when it returns. uv__io_poll() can return without doing
* I/O (meaning: no callbacks) when its timeout expires - which means we
* have pending timers that satisfy the forward progress constraint.
*
* UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
* the check.
*/
uv__update_time(loop);
uv__run_timers(loop);
}

r = uv__loop_alive(loop);
if (mode == UV_RUN_ONCE || mode == UV_RUN_NOWAIT)
break;
}

/* The if statement lets gcc compile it to a conditional store. Avoids
* dirtying a cache line.
*/
if (loop->stop_flag != 0)
loop->stop_flag = 0;

return r;
}

4 参考资料

  1. 《深入浅出NodeJS》
  2. 深入理解Node.js:核心思想与源码分析
  3. 深入理解Node.js:核心思想与源码分析
  4. node源码详解(二 )—— 运行机制 、整体流程
  5. 从Chrome源码看浏览器的事件机制
  6. 事件循环机制 Event-Loop及其延伸
  7. 【朴灵评注】JavaScript 运行机制详解:再谈Event Loop
  8. 一次弄懂Event Loop(彻底解决此类面试问题)
  9. Event loop in JavaScript
  10. libevent github
  11. libevent org
  12. libuv github
  13. libuv org
  14. Node.js挖掘系列

最后更新: 2022年03月02日 03:32

原始链接: http://rawbin-.github.io/browser/2017-05-09-js-event-loop-src/

× 赞赏这个人~
打赏二维码